    //
//  citipadCityViewController.m
//  citipad
//
//  Created by Chih Yuan Liu on 3/10/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "citipadCityViewController.h"
#import "formSpotInfoViewController.h"
#import "CTPFlickrFirstFetcher.h"
#import "CTPSpot.h"
#import "CTPSpotModel.h"
#import "flickrFirstGrabber.h"
#import "citipadViewController.h"


@implementation citipadCityViewController

@synthesize scrollView;
@synthesize cityname;
@synthesize addSpotView;
@synthesize addSpotHolder;
@synthesize titleImageView;


NSString* _cityname;
CTPSpotModel *spotModel;
NSMutableArray *grabbers;

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/

-(void)cleanContent{
	for(flickrFirstGrabber * grabber in grabbers){
		[grabber requireStop];
	}
	UIView * view;
	for(view in [scrollView subviews]){
		[view removeFromSuperview];
	}
}

- (void) layoutContent{
	UIImageView *view = nil;
	NSArray *subviews = [scrollView subviews];
	
	// reposition all image subviews in a horizontal serial fashion
	int i = 0;
	for (view in subviews)
	{
		if ([view isKindOfClass:[UIView class]] && view.tag > 0)
		{
			CGFloat curYLoc = 46;
			CGFloat curXLoc = 156 * (i) + 49;
			CGRect frame = view.frame;
			frame.origin = CGPointMake(curXLoc, curYLoc);
			view.frame = frame;
			
			i++;
		}
	}
	
	// set the content size so it can be scrollable
	[scrollView setContentSize:CGSizeMake((10 * 100), [scrollView bounds].size.height)];
	
}

-(void)dynamicAddSpotView{
	if(spotModel != nil){
		int count = [spotModel GetCount];
		
		int const labelheight = 21;
		int const labelwidth = 140;
		int const imageheight = 140;
		int const imagewidth = 140;
		
		for (int i = 0; i < count; i++){
			CTPSpot *spot = [spotModel GetItemAtIndex:i];
			
			UIImage *image = [UIImage imageNamed:@"c0.png"];
			UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
			
			[imageView addGestureRecognizer:
			 [[[UILongPressGestureRecognizer alloc] initWithTarget:self
															action:@selector(longPress:)] autorelease]];
			
			[imageView addGestureRecognizer:
			 [[[UITapGestureRecognizer alloc] initWithTarget:self
													  action:@selector(taponspot:)] autorelease]];
			
			UIView *holder = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 156, 200)];
			UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(9, 14, labelwidth , labelheight)];
			label.tag = i;
			label.text = spot.name;
			label.backgroundColor = [UIColor clearColor];
			// image frame
			CGRect rect = CGRectMake(9,14 +labelheight +9,imagewidth, imageheight);//imageView.frame;
			rect.size.height = imageheight;
			rect.size.width = imagewidth;
			holder.tag = (i+1);
			CGRect holderrect = holder.frame;
			holderrect.size.height = 200;
			holder.frame = holderrect;
			imageView.frame = rect;
			imageView.tag = i;	// tag our images for later use when we place them in serial fashion
			imageView.userInteractionEnabled = YES;
			[holder addSubview:imageView];
			[holder addSubview:label];
			[scrollView addSubview:holder];
			
			flickrFirstGrabber * grabber = [[flickrFirstGrabber alloc]initWithImageView: imageView];
			[grabber grabImage:spot.imageKey fetchkey:spot.name];
			[grabbers addObject:grabber];
			[grabber release];
			
			
			[imageView release];
			[holder release];
			[label release];
			
		}
		addSpotHolder.tag = (count+1);
		[scrollView addSubview: addSpotHolder]; 
		[self layoutContent];
	}
}

-(void)longPress:(UILongPressGestureRecognizer*)sender {
	if (sender.state == UIGestureRecognizerStateEnded) {
		//NSLog(@"Long press Ended");
		UIImageView * view = (UIImageView*)[(UITapGestureRecognizer*)sender view];
		NSLog(@"%d", view.tag);
		UIAlertView *alert  = [[[UIAlertView alloc] initWithTitle: @"Sure to remove this?"
														  message: @""
														 delegate: self
												cancelButtonTitle:@"Not Now"
												otherButtonTitles:@"OK", nil] autorelease];
		[alert show];
		curSpotViewIndex = view.tag;
	}
	else {
		//NSLog(@"Long press detected.");
	}
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
	if(buttonIndex ==1){
		CTPSpot * spot = [spotModel GetItemAtIndex:curSpotViewIndex];
		[spotModel removeSpot:spot];
		[spot release];
		[self cleanContent];
		[self dynamicAddSpotView];
	}
}


-(void)taponspot:(UITapGestureRecognizer*)sender {
	UIImageView * view = (UIImageView*)[(UITapGestureRecognizer*)sender view];
	CTPSpot * spot = [spotModel GetItemAtIndex:view.tag];
	citipadViewController * viewController = [[citipadViewController alloc] init];
	[viewController setCityName:spot.cityName];
	[viewController setSpotName:spot.name];
	[self presentModalViewController:viewController animated:YES];	
}


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	scrollView.backgroundColor = 
	[UIColor colorWithPatternImage:[UIImage imageNamed:@"s2.png"]]; 
	[scrollView setContentSize:CGSizeMake((2 * 1000), [scrollView bounds].size.height)];
	
	cityname.text = _cityname;

	CTPFlickrFirstFetcher *fetcher = [CTPFlickrFirstFetcher alloc];
	fetcher.delegate = self;
	[fetcher getDataFromCtp:_cityname];
	
	[addSpotView addGestureRecognizer:
	 [[[UITapGestureRecognizer alloc] initWithTarget:self
											  action:@selector(onAddSpotTouch)] autorelease]];
	
	spotModel = [[CTPSpotModel alloc] initWithCityName:_cityname];
	
	grabbers = [[NSMutableArray alloc] init];
		
	[self dynamicAddSpotView];
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	return (interfaceOrientation ==
			UIInterfaceOrientationLandscapeLeft);
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}


- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}

-(void) setName:(NSString*) name{
	_cityname = name;
}

-(IBAction) goHome{
	[self.parentViewController.parentViewController dismissModalViewControllerAnimated:YES];
	[self.parentViewController dismissModalViewControllerAnimated:YES];
}

formSpotInfoViewController *spotform;

-(void) onAddSpotTouch{
	//spotform = [[formSpotInfoViewController alloc] init];
	spotform = [[formSpotInfoViewController alloc] initWithNibName:@"formSpotInfoViewController" bundle:nil];
	[spotform setCityName: cityname.text ];
	spotform.delegate = self;
	spotform.modalPresentationStyle = UIModalPresentationFormSheet;
	[self presentModalViewController:spotform animated:YES];
}

- (void)onOkTouch:(formSpotInfoViewController*)sender name:(NSString*)name{
	CTPSpot * spot = [[CTPSpot alloc] init];
	NSLog(@"%s, %@", __PRETTY_FUNCTION__, name);
	spot.name = name;
	spot.cityName = _cityname;
	if(spotModel != nil){
		[spotModel addSpot:spot];
	}
	[spot release];
	[self cleanContent];
	[self dynamicAddSpotView];
}

- (void)onModalDismiss:(formSpotInfoViewController*)sender{
}

- (void)flickrFirstFetcherBegin:(CTPFlickrFirstFetcher*)sender{}
- (void)flickrFirstFetcherEnd:(CTPFlickrFirstFetcher*)sender{}
- (void)flickrFirstFetcherSucceeded:(CTPFlickrFirstFetcher*)sender data:(NSData*)data{
	UIImage *image = [UIImage imageWithData:data];
	[self.titleImageView setImage:image];
	NSLog(@"recieved data");
}
- (void)flickrFirstFetcherFailed:(CTPFlickrFirstFetcher*)sender{}

@end
